package cn.jdx.tools.md4img.tools;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class JdxToolsDownload {
    public static void downloadFile(String remoteFilePath, String localFilePath) {
        URL url = null;
        HttpURLConnection httpUrl = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        File f = new File(localFilePath);
        try {
            url = new URL(remoteFilePath);
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            bis = new BufferedInputStream(httpUrl.getInputStream());
            bos = new BufferedOutputStream(new FileOutputStream(f));
            int len = 2048;
            byte[] buffer = new byte[len];
            while ((len = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            bos.flush();
            bis.close();
            httpUrl.disconnect();
        } catch (Exception e) {
            //尝试第二次下载
            if (remoteFilePath.contains("////")){
                System.out.println("[尝试第二次下载]");
                remoteFilePath = remoteFilePath.replaceFirst("////","//");
                System.out.println("[下载路径]:"+remoteFilePath);
                System.out.println("[目标路径]:"+localFilePath);
                downloadFile(remoteFilePath, localFilePath);
                return;
            }else{
                e.printStackTrace();
            }
        } finally {
            try {
                if (bis!=null){
                    bis.close();
                }
                if (bos!=null){
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
